package com.qianbei.view.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.qianbei.R;
import com.qianbei.bean.GetBindBean1;
import com.qianbei.bean.GetBindBean2;
import com.qianbei.bean.GetBox;
import com.qianbei.common.adapter.CommonAdapter;
import com.qianbei.common.adapter.ViewHolder;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.MyApplication;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.view.BoxUPActivity;
import com.qianbei.view.EpcDataBase;
import com.qianbei.view.binding.AddBingActivity;
import com.qianbei.view.db.Box;
import com.qianbei.view.db.BoxDb;
import com.qianbei.view.orm.DaoSession;
import com.qianbei.view.orm.RFID;
import com.qianbei.view.orm.RFIDDao;
import com.qianbei.view.transport.EmptyUPActivity;
import com.qianbei.view.util.MessageCallback;

import org.greenrobot.greendao.query.QueryBuilder;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by gaoml on 2018/2/8.
 */

public class ScanAdapter extends CommonAdapter<EpcDataBase> {

    private Set<String> alreadyGetBoxNum = new HashSet<String>();
    private Context context;
    private TextView status;
    private TextView stat;
    private boolean shortTxt;
    private BoxDb boxDb;

    private MessageCallback delCallback;

    public void setShortTxt(boolean shortTxt) {
        this.shortTxt = shortTxt;
    }

    public void setStat(TextView stat) {
        this.stat = stat;
    }

    public TextView getStatus() {
        return status;
    }

    public void clearAlreadyGetBoxNum() {
        this.alreadyGetBoxNum.clear();
    }

    public void setStatus(TextView status) {
        this.status = status;
    }

    private final String[] boxTypeStr = {"医废小箱", "医废大箱", "医塑小箱", "医塑大箱"};

    public ScanAdapter(Context context, List<EpcDataBase> data, int itemLayoutId) {
        super(context, data, itemLayoutId);
        this.context = context;
        this.boxDb = new BoxDb(context);
    }

    public void setDelCallback(MessageCallback delCallback) {
        this.delCallback = delCallback;
    }

    public void show(final int position) {
        EpcDataBase epcData = mDatas.get(position);
        String msg = "确认删除周转箱？";
        if (epcData != null) {
            if (epcData.getBoxId() != null && epcData.getBoxId().trim().length() > 0) {
                msg = "确认删除周转箱(" + epcData.getBoxId() + ")？";
            } else if (epcData.getEpc() != null && epcData.getEpc().trim().length() > 0) {
                msg = "确认删除周转箱(" + epcData.getEpc() + ")？";
            }
        }
        AlertDialog dialog = new AlertDialog.Builder(mContext)
//                .setTitle("是否绑定此车")//设置对话框的标题
                .setMessage(msg)//设置对话框的内容
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        delete(position);
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }

    public void delete(int position) {
        EpcDataBase epcData = mDatas.get(position);
        if (epcData != null && !TextUtils.isEmpty(epcData.getEpc())) {
            alreadyGetBoxNum.remove(epcData.getEpc());
            try {
                DaoSession daoSession = ((MyApplication) context.getApplicationContext()).getDaoSession();
                RFIDDao rfidDao = daoSession.getRFIDDao();
                QueryBuilder<RFID> qb = rfidDao.queryBuilder();
                qb.where(RFIDDao.Properties.Rfid.eq(epcData.getEpc()));
                List<RFID> res = qb.list();

                if (res != null && res.size() > 0) {
                    rfidDao.deleteInTx(res.toArray(new RFID[]{}));
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (epcData != null && !TextUtils.isEmpty(epcData.getBoxId())) {
            alreadyGetBoxNum.remove(epcData.getBoxId());
            try {
                DaoSession daoSession = ((MyApplication) context.getApplicationContext()).getDaoSession();
                RFIDDao rfidDao = daoSession.getRFIDDao();
                QueryBuilder<RFID> qb = rfidDao.queryBuilder();
                qb.where(RFIDDao.Properties.BoxNum.eq(epcData.getBoxId()));
                List<RFID> res = qb.list();

                if (res != null && res.size() > 0) {
                    rfidDao.deleteInTx(res.toArray(new RFID[]{}));
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        mDatas.remove(position);
        notifyDataSetChanged();
        delCallback.call();

    }

    @Override
    public void convert(final ViewHolder helper, final EpcDataBase item, final int position) {
        helper.setText(R.id.show_data, item.toString());
        if (!TextUtils.isEmpty(item.boxType)) {
            helper.setText(R.id.box_type, item.boxType);
            helper.getView(R.id.box_type).setVisibility(View.VISIBLE);
        } else {
            helper.getView(R.id.box_type).setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(item.boxId)) {
            helper.setText(R.id.box_no, item.boxId);
            helper.getView(R.id.box_no).setVisibility(View.VISIBLE);
        } else {
            helper.getView(R.id.box_no).setVisibility(View.GONE);
        }

        View.OnClickListener bindListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                EpcDataBase epcData = mDatas.get(position);
                //如果没有箱子编号 或 箱子编号以L开始，可点击RFID到绑定周转箱界面

                Intent i = new Intent(mContext, AddBingActivity.class);
                i.putExtra("rfid", epcData.getEpc());
                i.putExtra("boxNum", epcData.getBoxId());
                i.putExtra("boxType", epcData.getTypeValue());


                ((BaseActivity) mContext).startActivityForResult(i, 1);

            }
        };

        helper.getView(R.id.show_data).setOnClickListener(bindListener);
        helper.getView(R.id.box_no).setOnClickListener(bindListener);

        helper.getView(R.id.dele_data).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show(position);
            }
        });


    }


    public void updateStatusText() {
        updateStatusText(false);
    }


    public void updateStatusText(boolean shortTxt) {
        int small = 0;
        int big = 0;
        if (mDatas == null) {
            return;
        }

        for (EpcDataBase epc : mDatas) {
            if (epc.typeValue != null) {
                if (epc.typeValue.equals("1") || epc.typeValue.equals("3")) {
                    small++;
                } else if (epc.typeValue.equals("2") || epc.typeValue.equals("4")) {
                    big++;
                }
            }
        }

        String boxCount = "大箱: " + big + "  小箱: " + small;
        if (shortTxt) {
            boxCount = "大: " + big + "  小: " + small;
        }
        int remained = mDatas.size() - small - big;
        if (remained > 0) {
            boxCount += "  箱号装车: " + remained;
        }

        //没网情况下得不到大小箱数
        if (small == 0 && big == 0 && remained == 0) {
            boxCount = "大箱: 0  小箱: 0";
        }
        if (status != null) {
            status.setText(boxCount);
        }

    }


    public String getStatInfo() {
        int small = 0;
        int big = 0;
        if (mDatas == null || mDatas.size() == 0) {
            return "";
        }

        for (EpcDataBase epc : mDatas) {
            if (epc.typeValue != null) {
                if (epc.typeValue.equals("1") || epc.typeValue.equals("3")) {
                    small++;
                } else if (epc.typeValue.equals("2") || epc.typeValue.equals("4")) {
                    big++;
                }
            }
        }

        String boxCount = "大箱: " + big + "  小箱: " + small;
        int remained = mDatas.size() - small - big;
        if (remained > 0) {
            boxCount += "  箱号装车: " + remained;
        }

        //没网情况下得不到大小箱数
        if (small == 0 && big == 0) {
            boxCount = "大箱: 0  小箱: 0";
        }

        return boxCount;
    }

    public void updateStat() {
        if (stat != null) {
            stat.setText(getStatInfo());
        }
    }
}
